var createError = require('http-errors');
var express = require('express');
// var expressWs = require("express-ws");

var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bioscopeRouter = require('./routes/bioscope');
var movieRouter = require('./routes/movie');
// var videoRoomSocketRouter = require('./routes/videoRoomSocket');
//搭建服务器
var app = express();
process.app = app;//方便在其他地方使用app获取配置
//绑定图片服务器
//production <-----> dev
// let dirNam = "D:\\Gitee\\bioscope";
let dirNam = "/usr/yuansong_web/bioscope";
require('./pictureConfig.js')(dirNam, app);//所有配置
var mode = app.get('mode');
var piConfig = app.get(mode);
require('./controllers/' + mode + '/Controller.js');
require('http').createServer(app).listen(piConfig.port, function () {
  console.log('%s已经启动,正监听:%s', piConfig.name, piConfig.port);
});
//通过执行以下的方法，会在现有的 app 实例上绑定 websocket 协议的封装方法，在调用该方法时，其语法类似 express 提供的 get、post、put 等方法：
// var http = require('http');
// var server = http.createServer(app);
// expressWs(app);
// app.ws('/socketTest',function(ws,req){
//   ws.send('你连接成功了')
//   ws.on('message',function(msg){
//     console.log('message 收到了')
//   })
// })

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/bioscope', bioscopeRouter);
app.use('/api/movie',movieRouter);
// app.use('/api/videoRoomSocket',videoRoomSocketRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
